# -*- coding: utf-8 -*-
"""
summary:
    转换助手类
author:
    李华顺 <huacnlee@gmail.com>
"""

def to_int(str,default=-1):
    """
    summary:
        转int型
    params:
        str    要转换的值，内容为整数
        default    无法转换时用什么代替[默认-1]
    """
    try:
        return int(str)
    except:
        return default

def to_float(str,default=-1):
    """
    summary:
        转float型
    params:
        str    要转换的值，内容为整数
        default    无法转换时用什么代替[默认-1]
    """
    try:
        return float(str)
    except:
        return default
    
def ip_to_int (ip):
    """
    summary:
        将IP转成int
    author:
        sshsiung <http://blog.ssh.tw/>
    """
    ips = ip.split(".")
    return int(ips[0]) * 16777216 + int(ips[1]) * 65535 + int(ips[2]) * 256 + int(ips[3])
 
 
# 將數字轉換 IP
def int_to_ip (ip_int):
    """
    summary:
        将int的IP转成str的IP
    author:
        sshsiung <http://blog.ssh.tw/>
    """
    ip1,t = ip_int / 16777216,ip_int % 16777216
    ip2,t = t / 65535, t % 65535
    ip3,ip4 = t / 256, t % 256
 
    if ip4:
        ip = "%d.%d.%d.%d" % (ip1,ip2,ip3,ip4)
    else:
        ip = None
 
    return ip
 
def get_ip_range(start_ip,stop_ip):
    """
    summary:
        计算两个IP的范围，并返回IP清单
    author:
        sshsiung <http://blog.ssh.tw/>
    """
    start_ip_int, stop_ip_int = ip_to_int(start_ip),ip_to_int(stop_ip)
 
    ips = []
    for i in range(stop_ip_int - start_ip_int + 1):
        ip =  int_to_ip(start_ip_int + i)
        if ip:
            ips.append(ip)
 
    return ips

# test
if __name__ == "__main__":
    ip1 = ip_to_int("61.188.138.191")
    print ip1
    
    print int_to_ip(ip1)
    print get_ip_range("192.168.1.255", "192.168.2.80")